<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\User;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
		$data = DB::table('users')
		->where(function($query) use ($request){
			// 查询数据
			if(!empty($request->input('username'))){
				$request->username = trim($request->username);
				$query->where('username', 'like', '%'. $request->username .'%');
			}
			if(!empty($request->nickname)){
				$request->nickname = trim($request->nickname);
				$query->where('nickname', 'like', '%' . $request->nickname . '%');
			}
			if(!empty($request->time1)){
				$query->where('lastlogin', 'like', '%' . $request->time1 . '%');
			}
			if(!empty($request->time2)){
				$query->where('lastlogin', 'like', '%' . $request->time2 . '%');
			}
		})
		->orderBy('id')
		->paginate(10);
		// 给分页追加查询参数
		$data = $data->appends(['username' => $request->input('username'), 'nickname' => $request->input('nickname'), 'time1' => $request->input('time1'), 'time2' => $request->input('time2')]);
		return view('admin/user/index')->with('data', $data)->with('request', $request);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('admin/user/create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // 表单验证
        $this->validate($request, [
            'username' => 'required|regex:/\w{3,20}/|unique:users',
            'password' => 'required',
        ],[
            'username.required' => '用户名不能为空',
            'username.regex' => '用户名长度为3-20位',
            'username.unique' => '用户名不能重复',
            'password.required' => '密码不能为空',
        ]);
     
        $data = $request->except('_token');
        $model = new User;
        $data['hash'] = mt_rand(1000,9999);
        $model->username = $data['username'];
        $model->nickname = !empty($data['nickname']) ? $data['nickname'] : '';
        $model->password = md5(md5($data['password'].$data['hash']));
        $model->hash = $data['hash'];
        $model->face = '';
        $model->lastlogin = 0;
        if ($model->save($data)) {
            return redirect('/admin/user/index');
        } else {
            return redirect('/admin/user/create');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
		$olddata = DB::table('users')->find($id);
		return view('admin/user/edit')->with('olddata', $olddata);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
		// 表单验证
		$rule = new \Illuminate\Validation\Rule;
		$this->validate($request, [
		    'username' => 'required|regex:/\w{3,20}/',
		    'username' => $rule->unique('users')->ignore($id),
		],[
		    'username.required' => '用户名不能为空',
		    'username.regex' => '用户名长度为3-20位',
		    'username.unique' => '用户名不能重复',
		]);
		     
		$data = $request->except(['_token','faceimg']);
		$model = new User;
		$data['hash'] = mt_rand(1000,9999);

		if(!empty($data['password'])){
			$data['password'] = md5(md5($data['password'].$data['hash']));
			echo 1;
		} else {
			unset($data['password']);
			unset($data['hash']);
			echo 2;
		}

		if ($model->where('id', '=', $id)->update($data)) {
		    return redirect('/admin/user/index');
		} else {
		    return redirect('/admin/user/edit/'.$data['id']);
		}
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
		if($id != 1){
			DB::table('users')->where('id', '=', $id)->delete();
		}
		return redirect('/admin/user/index');
    }
	
	/**
	 * 批量删除
	 */
	public function dels(Request $request)
	{
		if($ids = $request->input('ids')){
			DB::table('users')->whereIn('id', $ids)->where('id', '!=', '1')->delete();
		}
		return redirect('/admin/user/index');
	}
	
	public function upload(Request $request)
	{
		// 检测是否有文件上传
		if ($request->hasFile('faceimg')) {
			// 微秒时间戳
			$file_name = str_replace(".","",microtime(true)) . mt_rand(1000, 9999);
			// 原始文件后缀
			$type = $request->file('faceimg')->getClientOriginalExtension();
			// 移动文件到目录
			$request->file('faceimg')->move('./upload/face/', 'face_' . $file_name . '_face.' . $type);
			// 返回结果
			$arr = array('state'=>1, 'msg'=>'', 're'=>'/upload/face/face_' . $file_name . '_face.' . $type);
			echo json_encode($arr);
		}
		// dump($request->all());
	}
}
